package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.concurrent.TimeUnit;

/**
 * 使用redis 完成分布式锁
 * @author LENOVO
 * @Date 2022-12-11
 */
public class RedisLock implements ILock {

    private String name;
    private StringRedisTemplate stringRedisTemplate;
    private final String LOCK_PREFIX="lock:";
    private final String UUID_PREFIX=UUID.randomUUID(true).toString()+"-";
    public RedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean tryLock(Long time) {
        // 生成线程id标识
        String threadId = UUID_PREFIX + Thread.currentThread().getId();
        // 获取锁
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(LOCK_PREFIX + name, threadId, time, TimeUnit.SECONDS);
        return aBoolean;
    }

    @Override
    public void unLock() {
        // 获取锁的值
       String s = stringRedisTemplate.opsForValue().get(LOCK_PREFIX + name);
       // 判断是否为自己线程的锁
        if (s.equals(UUID_PREFIX+Thread.currentThread().getId())){
            stringRedisTemplate.delete(LOCK_PREFIX+name);
        }
    }
}
